﻿using Polly;
using Polly.Extensions.Http;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;

namespace Shared.Service.Http.Polly
{
    public class PolicyProvider
    {
        public static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy(int retryCount)
        {
            return HttpPolicyExtensions
              .HandleTransientHttpError()//异常或者非200的响应
              //.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
              .WaitAndRetryAsync(retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
        }
        public static IAsyncPolicy<HttpResponseMessage> GetRetryPolicyWithJitter(int retryCount,int randomMaxValue)
        {
            Random jitterer = new Random();
            return Policy<HttpResponseMessage>.HandleResult(resultPredicate=>!resultPredicate.IsSuccessStatusCode).WaitAndRetryAsync(retryCount,  retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)) + TimeSpan.FromMilliseconds(jitterer.Next(0, randomMaxValue)) );
        }

        public static IAsyncPolicy<HttpResponseMessage> GetCircuitBreakerPolicy(int handledEventsAllowedBeforeBreaking,int durationSecondOfBreak)
        {
            return HttpPolicyExtensions
                .HandleTransientHttpError()
                .CircuitBreakerAsync(handledEventsAllowedBeforeBreaking, TimeSpan.FromSeconds(durationSecondOfBreak));
        }
    }
}
